﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using ScaleDataInterpreter;
using clf.weighing.entity;
using Timer = System.Threading.Timer;

namespace weighing
{
    /// <summary>
    /// TestScaleWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestScaleWindow : GlowWindow
    {

        protected Timer? mTimer;
        protected SerialPort? mSerialPort = null;
        protected IScaleDataInterpreter? mScaleDataInterpreter;
        private Scale? mCurrScale = new ();
        public TestScaleWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);

            this.Closing += TestScaleWindow_Closing;
        }

        private void TestScaleWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DisposeTimer();
            DisposeSerialPort();
        }

        private void GlowWindow_ContentRendered(object sender, EventArgs e)
        {
            if (this.brandCb.ItemsSource == null)
            {
               var list = ScaleBrandDao.Instance.GetList();
                var source = list?.Select(i => new ScaleBrandVo(i)).ToList();
                this.brandCb.ItemsSource = source;
            }
            this.comCb.ItemsSource = SerialPort.GetPortNames();           
        }

        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            DisposeTimer();
            DisposeSerialPort();
        }

        protected void ReadScaleData()
        {
            DisposeSerialPort();
            try
            {
                mSerialPort = new SerialPort
                {
                    BaudRate = (int)mCurrScale.baudRate == 0 ? Convert.ToInt32(this.rateCb.Text) : (int)mCurrScale.baudRate,
                    PortName = mCurrScale.com == null ? this.comCb.Text : mCurrScale.com,
                    DataBits = 8,
                    StopBits = StopBits.One,
                    Parity = Parity.None,
                };
            }
            catch (Exception ex)
            {
                this.msgLbox.Items.Add(new ListBoxItem() { Foreground = System.Windows.Media.Brushes.Red, Content = "错误：" + ex.Message });
            }

            //设置当前显示控制的解释器。
            mScaleDataInterpreter = DataInterpreter.GetDataInterpreter((int)ScaleBrandType.YH, mSerialPort);
        }

        private void ShowScaleData()
        {
            DisposeTimer();

            if (mSerialPort != null && mSerialPort.IsOpen == false)
            {
                try
                {
                    mSerialPort.Open();
                }
                catch (Exception e)
                {
                    this.msgLbox.Items.Add("串口打开失败：" + e.Message);
                }
            }
            if (mSerialPort != null && mSerialPort.IsOpen == true)
            {
                mTimer = new Timer(SerialPortCallBack, 1, 1000, 1000);
            }
        }
        /// <summary>
        /// 显示数据
        /// </summary>
        /// <param name="stae"></param>
        private void SerialPortCallBack(Object stae)
        {
            ScaleDataResult result = mScaleDataInterpreter.ReadValue();
            if (result.ErrCode == 0)
            {
                this.Dispatcher.Invoke(() =>
                {
                    this.msgLbox.Items.Add("读到数据：" + result.Value);
                    this.wweighing.Text = result.Value.ToString();
                });
            }
            else
            {
                this.Dispatcher.Invoke(() =>
                {
                    this.msgLbox.Items.Add("读取数据失败：" + result.Msg + " === " + DateTime.Now.ToString());
                    this.wweighing.Text = "123";
                });
            }
        }


        protected void DisposeSerialPort()
        {
            if (mSerialPort != null)
            {
                if (mSerialPort.IsOpen == true)
                {
                    mSerialPort.Close();
                }
                mSerialPort.Dispose();
            }
        }

        protected void DisposeTimer()
        {
            if (mTimer != null)
            {
                mTimer.Dispose();
                mTimer = null;
            }
        }

        private void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            ReadScaleData();
            ShowScaleData();
        }

        private void GlowWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DisposeSerialPort();
            DisposeTimer();
        }

        private void RateCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.rateCb.SelectedIndex < 0) return;
            this.mCurrScale.baudRate = Convert.ToInt32(((ComboBoxItem)this.rateCb.SelectedItem).Content);
        }

        private void ComCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is System.Windows.Controls.ComboBox cb)
            {
                if (cb.SelectedIndex > -1)
                {
                    var com = this.comCb.SelectedItem.ToString();
                    mCurrScale.com = com;
                }
            }
        }

        private void BrandCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            this.msgLbox.Items.Clear();
        }
    }
}
